<?php
/**
 * ClassName: CasesService
 * Description:
 * @Author 周昌
 * @Create 2023/12/7 10:54
 */

namespace service\admin;


use Exception;
use libs\Tool;
use model\ArchivesModel;
use model\CasesModel;
use model\HospitalModel;
use model\PrescriptModel;
use model\TreatmentModel;
use model\TreatmentServicesModel;
use model\WaitModel;
use service\BaseService;
use think\Db;

class CasesService extends BaseService
{
    protected static $model = 'model\CasesModel';
    public static $payment_status = [0 => '待支付', 1 => '已支付'];
    public static $payment_status_index = ['to_be_pay' => 0, 'paid' => 1];
    public static $pay_type = [0 => '卡支付', 1 => '线下支付'];
    public static $pay_type_index = ['card_pay' => 0, 'offline_pay' => 1];
    public static $treatment_status = [0 => '进行中', 1 => '已完成'];//治疗服务状态
    public static $treatment_status_index = ['progress' =>0,'completed'=> 1];//治疗服务状态

    //支付状态select选择
    public static function casePaymentSelect()
    {
        static $case_payment_select = [];
        if (empty($case_payment_select)) {
            foreach (self::$payment_status as $k => $v) {
                $row = [];
                $row['id'] = $k;
                $row['name'] = $v;
                $case_payment_select[] = $row;
            }
            array_unshift($case_payment_select, ['id' => '', 'name' => '-----请选择-----']);
        }
        return $case_payment_select;
    }

    //处方支付类型下拉选择
    public static function casePayTypeSelect()
    {
        static $case_pay_type_select = [];
        if (empty($case_pay_type_select)) {
            foreach (self::$pay_type as $k => $v) {
                $row = [];
                $row['id'] = $k;
                $row['name'] = $v;
                $case_pay_type_select[] = $row;
            }
            array_unshift($case_pay_type_select, ['id' => '', 'name' => '-----请选择-----']);
        }
        return $case_pay_type_select;
    }

    /**
     * #User: Administrator
     * #Time: 2023/12/9 10:39
     * #Author:周昌
     * #Description:case 添加/修改
     * @param $data
     * @param $wait_id 排号表id
     * @param null $id case 主键id
     * @return array
     */
    public static function addEdit($data, $wait_id, $id = null)
    {
        //将数组转话为json字符串
        $data['look_over'] = empty(array_filter($data['look_over'])) ? '' : json_encode($data['look_over']);
        $data['smell'] = empty(array_filter($data['smell'])) ? '' : json_encode($data['smell']);
        $data['pulse_taking'] = empty(array_filter($data['pulse_taking'])) ? '' : json_encode($data['pulse_taking']);
        if ($id) {
            return self::edit($id, $data);
        } else {
            $data['payment_status'] = 0;//待支付
            $data['addtime'] = time();
//            $res=self::add($data);
            Db::startTrans();
            try {
                $id = self::$model::insertGetId($data);
                if (!$id) {
                    Db::rollback();
                    return Tool::Error('case添加失败');
                }
                $wait_res = WaitModel::updateInfo(['id' => $wait_id], ['case_id' => $id,'status'=>WaitService::$wait_status_index['progress'],'update_time'=>time()]);
                if ($wait_res === false) {
                    Db::rollback();
                    return Tool::Error('排号更新失败');
                }
                Db::commit();
                return Tool::Success('成功', ['case_id' => $id]);
            } catch (Exception $exception) {
                Db::rollback();
                return Tool::Error($exception->getMessage());
            }
        }

    }

    // 获取处理之后的case 数据
    public static function getCaseInfo($id)
    {
        $data = self::$model::getInfo(['id' => $id]);
        if (!empty($data)) {
            $data['look_over'] = empty($data['look_over']) ? '' : json_decode($data['look_over'], true);
            $data['smell'] = empty($data['smell']) ? '' : json_decode($data['smell'], true);
            $data['pulse_taking'] = empty($data['pulse_taking']) ? '' : json_decode($data['pulse_taking'], true);
        } else {
            $data = [];
        }
        return $data;
    }
    //病历 支付操作
    public static function casePay($id,$data)
    {
        $info=self::$model::getInfo(['id'=>$id]);
//        $member_id=ArchivesModel::getValue(['id'=>$info['archives_id']],'member_id');
        $archives_info=ArchivesModel::getInfo(['id'=>$info['archives_id']],'member_id,member_info_id,name');

        //床位判断+治疗服务完成判断
        $wait_info=WaitModel::getInfo(['case_id'=>$id,'type'=>1],'id,status,bed_id');
        if(!$wait_info['bed_id']&&$data['money']>0){
            return Tool::Error('尚未分配床位，无法支付');
        }
        $treatment_services_res=TreatmentServicesModel::getInfo(['case_id'=>$id,'status'=>0]);
        if($treatment_services_res){
            return Tool::Error('尚有为完成的治疗服务，无法支付');
        }
        Db::startTrans();
        try{
            //更新case病例表
            $data['payment_status']=self::$payment_status_index['paid'];
            $data['pay_time']=time();
            $data['treatment_status']=self::$treatment_status_index['completed'];
            $res=self::edit($id,$data);
            if($res['code']==0){
                Db::rollback();
                return Tool::Error('病历更新失败');
            }
            //支付添加记录
            if($data['pay_type']){
                //线下支付 线下支付现在也存储在card_log
                $insert=[
                    'pay_type'=>CardLogService::$log_pay_type_index['offline_pay'],
                    'member_id'=>$archives_info['member_id'],
                    'member_info_id'=>$archives_info['member_info_id'],
                    'money'=>$data['money'],
                    'pay_money'=>$data['money'],
                ];
                $card_log=CardLogService::addCardLog(CardLogService::$card_log_type_index['treatment'],$insert,$id);
                if($card_log['code']==0){
                    Db::rollback();
                    return Tool::Error('线下消费记录添加失败');
                }
//                $payment_log=PaymentLogService::addPaymentLog($insert);
//                if($payment_log['code']==0){
//                    Db::rollback();
//                    return Tool::Error('线下支付记录添加失败');
//                }
                //添加线下支付消息
                $message_res=MessageService::addMessage($archives_info['member_id'],MessageService::$message_type_index['consume'],$data['money'],null,null);
                if($message_res['code']==0){
                    Db::rollback();
                    return Tool::Error('线下支付消息添加失败');
                }
            }else{
                //卡支付
                $log_insert=[
                    'type'=>CardLogService::$card_log_type_index['treatment'],
                    'pay_type'=>CardLogService::$log_pay_type_index['card_pay'],
                    'member_id'=>$archives_info['member_id'],
                    'member_info_id'=>$archives_info['member_info_id'],
                    'card_id'=>$data['card_id'],
                    'money'=>$data['money'],
                    'case_id'=>$id,
                ];
                //卡消费+卡消费记录
                $consume=CardService::cardConsume(['id'=>$data['card_id']],$data['money'],$log_insert);
                if($consume['code']==0){
                    Db::rollback();
                    return Tool::Error($consume['msg']);
                }
                //卡消费记录
//                $card_log=CardLogService::addCardLog(CardLogService::$card_log_type_index['treatment'],$log_insert,$id);
//                if($card_log['code']==0){
//                    Db::rollback();
//                    return Tool::Error('卡消费记录添加失败');
//                }
                //卡支付消息
                $message_res=MessageService::addMessage($archives_info['member_id'],MessageService::$message_type_index['consume'],$data['money'],$data['card_id'],null);
                if($message_res['code']==0){
                    Db::rollback();
                    return Tool::Error('卡支付消息添加失败');
                }

            }
            //将wait治疗排号更新为已完成
            $wait_res=WaitService::status($wait_info['id'],WaitService::$wait_status_index['end']);
            if($wait_res['code']==0){
                Db::rollback();
                return Tool::Error('治疗排号状态更新失败');
            }
            //将床位清空
            $bed_res=BedService::setEmpty($wait_info['bed_id']);
            if($bed_res['code']==0){
                Db::rollback();
                return Tool::Error('清床失败');
            }
            Db::commit();
            return Tool::Success();

        }catch (\Exception $exception){
            Db::rollback();
            return Tool::Error($exception->getMessage());
        }
    }
    //完成的治疗服务人次统计，以月份为单位
    public static function personTimes($year=null,$hospital_id=null)
    {
        $year=$year??date('Y');
        $hospital_name=$hospital_id?HospitalModel::getValue(['id'=>$hospital_id],'name'):'全部医院';
        $data=[
            ['month'=>$year.'-01','count'=>0,'hospital_name'=>$hospital_name],
            ['month'=>$year.'-02','count'=>0,'hospital_name'=>$hospital_name],
            ['month'=>$year.'-03','count'=>0,'hospital_name'=>$hospital_name],
            ['month'=>$year.'-04','count'=>0,'hospital_name'=>$hospital_name],
            ['month'=>$year.'-05','count'=>0,'hospital_name'=>$hospital_name],
            ['month'=>$year.'-06','count'=>0,'hospital_name'=>$hospital_name],
            ['month'=>$year.'-07','count'=>0,'hospital_name'=>$hospital_name],
            ['month'=>$year.'-08','count'=>0,'hospital_name'=>$hospital_name],
            ['month'=>$year.'-09','count'=>0,'hospital_name'=>$hospital_name],
            ['month'=>$year.'-10','count'=>0,'hospital_name'=>$hospital_name],
            ['month'=>$year.'-11','count'=>0,'hospital_name'=>$hospital_name],
            ['month'=>$year.'-12','count'=>0,'hospital_name'=>$hospital_name]
        ];
        $where=[
            ['money','>',0],
            ['payment_status','=',self::$payment_status_index['paid']],
            ['addtime','>=',strtotime("$year-01-01 00:00:00")],
            ['addtime','<=',strtotime("$year-12-31 23:59:59")]
        ];
        if($hospital_id){
            $where[]=['hospital_id','=',$hospital_id];
        }
        $res=CasesModel::where($where)->field("DATE_FORMAT(FROM_UNIXTIME(addtime), '%Y-%m') as month,count(id) as count")->group('month')->select()->toArray();
        if(!empty($res)){
            $res=array_column($res,null,'month');
            foreach ($data as $k=>$v){
               if(isset($res[$v['month']])&&$res[$v['month']]['count']>0){
                    $data[$k]['count']=$res[$v['month']]['count'];
               }
            }
        }
        return json_encode(['rows'=>$data,"total" => count($data)], JSON_UNESCAPED_UNICODE);
    }
    //列表数据
    public static function getAjaxData($where)
    {
        $table = self::$model::alias('c')->leftJoin('archives a','a.id=c.archives_id')->leftJoin('member m','m.id=a.member_id')
           ->field("c.*,a.name,a.sex,CONCAT(m.real_name,'-',m.phone) as family_group")->order(['c.payment_status'=>'asc','c.id'=>'desc']);
        return self::tableJsonData($table, $where, function ($data) {
            $data['sex_name'] = MemberService::$sex[$data['sex']];
            $data['main_desc'] = Tool::strOmit($data['main_desc']);
            $data['analysis'] = Tool::strOmit($data['analysis']);
            $data['pay_type'] = self::$pay_type[$data['pay_type']] ?? '';
            $data['pay_time'] = $data['pay_time'] ?? '';
            $data['money'] = self::$pay_type[$data['pay_type']] ?? '';
            $data['payment_status'] = self::$payment_status[$data['payment_status']] ?? '';
            $data['hospital_name'] = $data['hospital_id'] ? HospitalService::getNameByKey($data['hospital_id'], '') : '';
            return $data;
        }, function ($data) {
            if (!empty($data)) {
                //查询各项治疗服务总金额
                $case_ids = array_column($data, 'id');
                $where=[
                    ['case_id','in',$case_ids],
                    ['status','=',TreatmentServicesService::$status_index['yes']],
                ];
                $sum_list = TreatmentServicesModel::where($where)->group('case_id')->column('case_id,sum(money)', 'case_id');
                //处方
                $prescript=PrescriptModel::getListColumn([['case_id','in',$case_ids]],'case_id,id','case_id');
                $data = array_map(function ($v) use ($sum_list,$prescript) {
                    $v['money'] = $sum_list[$v['id']] ?? 0;
                    $v['prescript_id'] = $prescript[$v['id']] ?? '';
                    return $v;
                }, $data);
            }
            return $data;
        });
    }


}